package com.shujia.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo9Join {
  def main(args: Array[String]): Unit = {

    //1、创建spark环境
    //创建配置文件对象
    val conf = new SparkConf()
    //指定spark执行默认，local：本地执行
    conf.setMaster("local")
    //spark 任务名
    conf.setAppName("wc")
    //创建spark上下文对象
    val sc = new SparkContext(conf)

    val namesRDD: RDD[(String, String)] = sc
      .parallelize(List(
        ("001", "张三"),
        ("002", "李四"),
        ("003", "王五"),
        ("004", "赵六"),
      ))

    val agesRDD: RDD[(String, Int)] = sc
      .parallelize(List(
        ("002", 23),
        ("003", 24),
        ("004", 25),
        ("005", 26),
      ))

    /**
     * inner join
     */
    val innerJoinRDD: RDD[(String, (String, Int))] = namesRDD.join(agesRDD)

    //整理数据
    innerJoinRDD
      .map {
        case (id: String, (name: String, age: Int)) =>
          (id, name, age)
      }
    //.foreach(println)

    /**
     * left join
     *
     * Option: 可选值，有两种值，有值和没有值
     */
    val leftJoinRDD: RDD[(String, (String, Option[Int]))] = namesRDD.leftOuterJoin(agesRDD)

    leftJoinRDD.map {
      //关联成功的处理方式
      case (id: String, (name: String, Some(age))) => (id, name, age)
      //没有关联成功的处理方式
      case (id: String, (name: String, None)) => (id, name, 0)
    }
    //.foreach(println)


    /**
     * full join
     */
    val fullJoinRDD: RDD[(String, (Option[String], Option[Int]))] = namesRDD.fullOuterJoin(agesRDD)

    fullJoinRDD.map {
      //关联成功的处理方式
      case (id: String, (Some(name), Some(age))) => (id, name, age)
      case (id: String, (None, Some(age))) => (id, "默认值", age)
      case (id: String, (Some(name), None)) => (id, name, 0)
    }
      .foreach(println)

  }

}
